"""
版本状态流转触发工具
在关联对象状态更新时触发版本状态流转检查
"""
from typing import Optional
from motor.motor_asyncio import AsyncIOMotorDatabase  # pyright: ignore[reportMissingImports]
from bson import ObjectId  # pyright: ignore[reportMissingImports]
import logging

logger = logging.getLogger(__name__)


async def trigger_version_transition_check(
    db: AsyncIOMotorDatabase,
    object_type: str,
    object_id: ObjectId,
    trigger_source: Optional[str] = None
):
    """
    触发版本状态流转检查
    
    当关联对象（任务、缺陷、需求）状态更新时，检查相关版本是否需要自动流转
    
    Args:
        db: 数据库连接
        object_type: 对象类型（task/defect/requirement）
        object_id: 对象ID
        trigger_source: 触发来源（可选，默认使用object_type）
    """
    try:
        if trigger_source is None:
            trigger_source = object_type
        
        # 查找关联的版本
        relation_collection_map = {
            "task": "version_task_relations",
            "defect": "version_defect_relations",
            "requirement": "version_requirement_relations"
        }
        
        collection_name = relation_collection_map.get(object_type)
        if not collection_name:
            logger.warning(f"未知的对象类型: {object_type}")
            return
        
        # 查找关联的版本ID列表
        relations = await db[collection_name].find(
            {f"{object_type}_id": object_id}
        ).to_list(length=None)
        
        if not relations:
            # 没有关联的版本，无需检查
            return
        
        version_ids = [rel["version_id"] for rel in relations]
        
        # 异步检查每个版本的状态流转
        from app.services.version_service import VersionService
        
        service = VersionService(db)
        
        # 批量检查版本流转（使用asyncio.gather并行处理）
        import asyncio
        
        tasks = [
            service.check_and_transition(version_id, trigger_source)
            for version_id in version_ids
        ]
        
        results = await asyncio.gather(*tasks, return_exceptions=True)
        
        # 记录结果
        for version_id, result in zip(version_ids, results):
            if isinstance(result, Exception):
                logger.error(
                    f"检查版本 {version_id} 状态流转失败: {str(result)}"
                )
            elif result:
                logger.info(
                    f"版本 {version_id} 状态自动流转: {result.get('from_status')} -> {result.get('to_status')}"
                )
        
        # 清除相关版本的完成度缓存
        from app.core.version_completion_cache import version_completion_cache
        
        for version_id in version_ids:
            version_completion_cache.invalidate_cache(version_id)
        
    except Exception as e:
        logger.error(
            f"触发版本状态流转检查失败: object_type={object_type}, "
            f"object_id={object_id}, error={str(e)}",
            exc_info=True
        )

